package com.zt.proxy.handler;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ReferenceConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import com.alibaba.dubbo.config.utils.ReferenceConfigCache;
import com.alibaba.dubbo.rpc.service.GenericService;
import com.alibaba.fastjson.JSONArray;
import com.zt.proxy.dto.ConnectDTO;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class DubboExecuteHandler {

    private ApplicationConfig buildApplicationConfig(String applicationName) {
        ApplicationConfig applicationConfig = new ApplicationConfig();
        applicationConfig.setName(applicationName);
        return applicationConfig;

    }

    private RegistryConfig buildRegistryConfig(ConnectDTO dto) {
        RegistryConfig registryConfig = new RegistryConfig();
        registryConfig.setAddress("zookeeper://" + dto.getConn());
        if(StringUtils.isNotBlank(dto.getGroup())){
            registryConfig.setGroup(dto.getGroup()); 
        }
        if(StringUtils.isNotBlank(dto.getVersion())){
            registryConfig.setVersion(dto.getVersion());
        }
        return registryConfig;
    }

    public GenericService buildGenericService(ConnectDTO dto) {
        ReferenceConfig<GenericService> reference = new ReferenceConfig<>();
        reference.setApplication(this.buildApplicationConfig(dto.getApplicationName()));
        reference.setRegistry(this.buildRegistryConfig(dto));
        reference.setInterface(dto.getServiceName());
        reference.setGeneric(true);
        reference.setProtocol("dubbo");
        ReferenceConfigCache cache = ReferenceConfigCache.getCache();
        return cache.get(reference);
    }
    
    public static void main(String[] args) {
        ApplicationConfig applicationConfig = new ApplicationConfig();
        applicationConfig.setName("ucc-core");
        RegistryConfig registryConfig = new RegistryConfig();
        registryConfig.setAddress("zookeeper://192.168.2.231:2181");
        ReferenceConfig<GenericService> reference = new ReferenceConfig<>();
        reference.setApplication(applicationConfig);
        reference.setRegistry(registryConfig);
        reference.setInterface("com.smy.ucc.service.SnsPostService");
        reference.setGeneric(true);
        reference.setProtocol("dubbo");
        ReferenceConfigCache cache = ReferenceConfigCache.getCache();
        GenericService service =  cache.get(reference);
        String[] parameterTypes = new String[]{"com.smy.ucc.dto.SnsPostDTO"};
        Object[] params = JSONArray.parseArray("[{'canReply':7771}]").toArray();
        Object res = service.$invoke("postList", parameterTypes, params);
        log.info("res",res);
    }
}
